package com.hyh.admin.config.security.userdetails;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyh.ad.common.constants.Constants;
import com.hyh.ad.common.constants.RedisConstant;
import com.hyh.ad.common.core.domain.login.LoginUser;
import com.hyh.ad.common.core.domain.model.SysUser;

import com.hyh.ad.common.core.redis.CacheClient;
import com.hyh.ad.common.core.redis.RedisCache;
import com.hyh.admin.sys.mapper.SysMenuMapper;
import com.hyh.admin.sys.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private CacheClient cacheClient;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();
        qw.eq(SysUser::getUsername, username);
        SysUser user = sysUserMapper.selectOne(qw);
        if(Objects.isNull(user))
            throw new UsernameNotFoundException("用户不存在");
        // 查询权限信息
        List<String> list = sysMenuMapper.selectAuthentication(user.getId());
        //去除[]符号
        if (!list.isEmpty()) {
            List<String> cleanedList = new ArrayList<>();
            for (String item : list) {
                // 去除开头和结尾的 [ 和 ]
                String cleanedItem = item.replaceAll("^\\[|\\]$", "");
                cleanedList.add(cleanedItem);
            }
            list.clear();
            list.addAll(cleanedList);
        }
        //将权限存入到redis
        cacheClient.setObject(RedisConstant.USER_PERMISSION_PREFIX + user.getId(), list, Constants.TOKEN_EXPIRATION, TimeUnit.MINUTES);
        return new LoginUser(user, list);
    }
}
